<template>
    <div>
        <div class="flex" style="margin-bottom: 1%">
            <a-tooltip content="请输入车号">
                <a-input v-model="objectData.car_no" placeholder="请输入车号" allow-clear style="width:calc((100% - 64px) / 6);margin-right:16px;" />
            </a-tooltip>
            <a-tooltip content="请选择客户">
                <a-select v-model="objectData.dept_id" :options="dept_list" allow-clear allow-search placeholder="请选择客户" :filter-option="filterOption" :field-names="{ value: 'id', label: 'name' }" style="width:calc((100% - 64px) / 6);margin-right:16px;" />
            </a-tooltip>
            <a-tooltip content="请选择运输方式">
                <a-select v-model="objectData.transport_type" :options="yunshuList" allow-clear allow-search placeholder="请选择运输方式"  :field-names="{ value: 'key', label: 'title' }" style="width:calc((100% - 64px) / 6);margin-right:16px;" />
            </a-tooltip>
            <a-tooltip content="请选择品名">
                <a-select v-model="objectData.goods_id" :options="goods_list" allow-clear allow-search placeholder="请选择品名" :filter-option="filterOption"  :field-names="{ value: 'id', label: 'name' }" style="width:calc((100% - 64px) / 6);margin-right:16px;" />
            </a-tooltip>
            <div class="flex" style="width:calc((100% - 64px) / 6);">
                <a-button type="primary" style="margin-right:16px;" @click="handleSouSuo(1)">搜索</a-button>
                <a-button @click="handleChongZhi(1)">重置</a-button>
            </div>
        </div>
        <div class="flex" style="margin-bottom: 1.5%">
            <a-tooltip content="请输入股道">
                <a-input v-model="work_line" placeholder="请输入股道" allow-clear style="width:calc((100% - 64px) / 6);margin-right:16px;" />
            </a-tooltip>
            <a-tooltip content="请输入顺位">
                <a-input v-model="transport_number" placeholder="请输入顺位" allow-clear style="width:calc((100% - 64px) / 6);margin-right:16px;" />
            </a-tooltip>
            
            
            <div class="flex" style="width:calc((100% - 64px) / 6);">
                <a-button type="primary" style="margin-right:16px;" @click="handleShezhi">批量设置</a-button>
            </div>
        </div>
        <a-table :scroll="{x:'100%'}" :data="chongGouList" :columns="columns" :pagination="false" row-key='id' ref="aTableRef" @row-click="rowClick" :row-selection="{type: 'checkbox',showCheckedAll: true,onlyCurrent: false,}"  v-model:selectedKeys="keys" @selection-change="setSelectedKeys">
            <template #dept_id="{ record,rowIndex }">
                <div v-if="record.dept">{{ record.dept.name }}</div>
                <div style="color:red;" v-if="!record.dept && record.is_nobody == 1">无主货</div>
            </template>
            <template #goods_id="{ record,rowIndex }">
                {{ record.goods_name }}
            </template>
            <template #car_no="{ record }">
                <div class="flex align_center justify_center">
                    <div style="color:red">{{ record.car_type }}</div>
                    <div style="">-</div>
                    <div>{{record.car_no}}</div>
                </div>
            </template>
            <template #is_load="{ record }">
                <a-switch v-model="record.is_load" />
            </template>
            
            
            <template #notice_time="{record,rowIndex}">
                <div @click.stop>
                <a-date-picker
                    style="width: 100%; "
                    show-time
                    v-model="record.notice_time"
                    format="YYYY-MM-DD HH:mm"
                    @ok="onOks($event,rowIndex)"
                />
                </div>
            </template>
            
            <template #work_line="{ record }">
                <div @click.stop>
                    <input v-model="record.work_line" placeholder="股道" type="text" class="input" style="width: 100%;" />
                </div>
                
            </template>
            <template #transport_number="{ record }">
                <div @click.stop>
                    <input v-model="record.transport_number" placeholder="顺位" type="text" class="input" style="width: 100%;" />
                </div>
            </template>
            <template #transport_type="{record,rowIndex}">
                {{ record.transport_type == 1?'集装箱':record.transport_type == 2?'整车':'批量快运' }}
            </template>
            <template #serve_type="{record,rowIndex}">
                {{record.serve_type == 1?'仓储':record.serve_type == 2?'配送':'自提'}}
            </template>
            <template #caozuo="{record,rowIndex}">
                <div @click.stop>
                    <a-link @click="handleTongshang(record,rowIndex)" v-if="rowIndex != 0">同上</a-link>
                </div>
            </template>
            <template #ec_id="{record,rowIndex}">
                <div @click.stop>
                    <a-link @click="openFile(record.ticket_number)">查看大票</a-link>
                </div>
            </template>
            
        </a-table>
        <div class="flex" style="justify-content: flex-end;margin-top: 1.5%;">
            <a-pagination :total="chongGouTotal" @change="handleChange" @page-size-change="handlePageSizeChange"  show-page-size show-total/>
        </div>
        <div class="flex" style="justify-content: flex-end;margin-top: 1.5%;" >
            <a-button type="primary" @click="handleQuePipei">确认装卸</a-button>
        </div>


        <a-modal :mask-closable="false" 
			v-model:visible="dpShow"
			title="查看大票"
			:footer="false"
            width="1400px"
                >
            <div v-for="(item,index) in dpUrl" :key="index">
                <a-spin :loading="daShpwloading" tip="请稍等..." dot  style="width:100%">
                    <iframe
                        ref="myIframe"
                        :src="item + '#zoom=100'"
                        style="width: 100%; height: 800px; border: none;"
                    ></iframe>
                </a-spin>
            </div>
            <div v-if="dpUrl.length == 0" >
                <a-spin :loading="true" tip="请稍等..." dot  style="width:100%">
                    <div style="width: 100%; height: 800px; border: none;"></div>
                </a-spin>
            </div>
		</a-modal>
    </div>
</template>




<script setup>
    import { ref, reactive, onMounted, onActivated, defineProps } from "vue";
    import predictionManage from "@/api/prediction/predictionManage";
    import commonApi from "@/api/common";
    import { pinyin } from "pinyin-pro"
    import { request } from "@/utils/request.js";
    import { Message } from "@arco-design/web-vue";
    import tool from '@/utils/tool'
    // 点击行 选中
    const env = ref(import.meta.env);

	// 点击行选中
	const aTableRef = ref(null)
	const rowClick = (e) => {
        console.log(e)
		if(keys.value.includes(e.id)){
			aTableRef.value.select(e.id,false)
		}else{
			aTableRef.value.select(e.id,true)
		}
	}
    
    const work_line = ref('')
    const transport_number = ref('')
    const emits = defineEmits(['succ'])
    const keys = ref([])
    const dept_list = ref([])   //  公司列表
    const contract_list = ref([])  // 合同列表
    const goods_list = ref([])  // 品名列表
    const objectData = ref({
        page:1,
        pageSize:10,
        // is_compled:1,
        is_load:1,
        car_no:'',
        prediciont_status:0,
        dept_id:'',
        transport_type:'',
        goods_id:""
    })
    const chongGouTotal = ref(0) 
    const yunshuList = ref([])
    const fuwuList = ref([])
    const chongGouList = ref([]) 
    const handleShezhi = ()=>{
        if(keys.value.length == 0){
        	return Message.error('请选择数据~')
        }
        
        chongGouList.value.map((v,i)=>{
            if(keys.value.includes(v.id)){
                v.work_line = work_line.value
                v.transport_number = transport_number.value
            }
        })	
    }
    
    const handleTongshang = (row,index)=>{
        if(index > 0){
            chongGouList.value[index].is_load = chongGouList.value[index - 1].is_load
            chongGouList.value[index].work_line = chongGouList.value[index - 1].work_line
            chongGouList.value[index].transport_number = chongGouList.value[index - 1].transport_number
        }else{
            Message.error('同上失败！')
        }
        console.log(chongGouList.value)
    }
    const handleSouSuo = ()=>{
        objectData.value.page = 1  
        handleChongGouList()
    }
    const handleChongZhi = ()=>{
        objectData.value.page = 1
        objectData.value.car_no = ''
        objectData.value.dept_id = ''
        objectData.value.transport_type = ''
        objectData.value.goods_id = ''
        handleChongGouList()
    }
    const dpShow = ref(false)
const filterOption = (v,option)=>{
    return option.keywords.some(keywords=>keywords.includes(v))
}
const daShpwloading = ref(false)
const dpUrl = ref('')
const openFile = (id) => {
    // 假设文件URL是http://example.com/file.pdf
    // const fileUrl = 'https://ec.95306.cn/goPdf?aqcnsfileId=' + id;
    let fileUrl = ""
    dpUrl.value = []
    dpShow.value = true
    const queryString = new URLSearchParams({ticket_numbers:id}).toString();
    fetch(`https://pdf.chuangxing.ren/api/index/get_pdf_url?${queryString}`,{
      headers:{
        'Content-Type': 'application/json',
      }
    })
    .then(response => response.json())
    .then(data => {
        if(data.code == 1){
            dpUrl.value = data.data
            daShpwloading.value = true
            setTimeout(() => {
                daShpwloading.value = false
            },1000)
        }else{
            Message.error(data.msg)
            dpShow.value = false
        }
      
    })
    .catch(error => console.error('Error:', error));

    
};
    
    const onOks = (e,index)=>{
        chongGouList.value[index].notice_time = e
    }
    
    const handleQuePipei = ()=>{
        if(keys.value.length != 0){
            let arr = []
            keys.value.map((v,i)=>{
                chongGouList.value.map((vv,ii)=>{
                    if(v == vv.id){
                        arr.push(vv)
                    }
                })
            })
            
            predictionManage.getComeSet({items:arr}).then(res=>{
                handleChongGouList()
                Message.success('装卸成功！')
                // emits('succ',false)
            })
        }else{
            Message.error('请选择数据~')
        }
    }
    const handleDeptList = () => {   //  获取公司列表
        request({
            url: 'system/dept/remote',
            method: 'post',
            data: {
            openPage: false,
            remoteOption: {
                filter: {
                type: ['=', 2],
                status: ['=',1]
                },
                select: ["id", "name"],
                sort: { id: "desc" }
            }
            }
        }).then(res => {
            let arr = []
            res.data.map((v,i)=>{
                v.keywords = [
                v.name,
                pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join(''),
                pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
                ]
                if(v.status == 1){
                arr.push(v)
                }
            })
            dept_list.value = res.data
        })
    }
    const handleContract = (id,index) => {   // 获取合同列表
        console.log('index:',index)
        chongGouList.value[index].dept_id = id
        request({
            url: 'system/userContract/remote_prediction?dept_id=' + id,
            method: 'get',
            params: {
            openPage: false,
            }
        }).then(res => {
            contract_list.value = res.data
        })
    }
    const hadnleChangeGoods = (e,index) => {   // 品名列表
        goods_list.value = []
        request({
            url: 'goods/manage/index',
            method: 'get',
            params:{
                pageSize:1000,
            }
        }).then(res => {
            let _data = res.data.items
            _data.map((v,i)=>{
                v.goods_id = v.id
            })
            _data.map((v,i)=>{
                v.keywords = [
                v.name,
                pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join(''),
                pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
                ]
            })
            // list = _data
            goods_list.value = _data
        })
    }
    const hadnleGoods = (e,index) => {   // 选择品名
        chongGouList.value[index].goods_id = e
    }
    const hadnleChangetransport_type = (e,index) => {   // 选择运输方式
        chongGouList.value[index].transport_type = e
    }
    const hadnleChangeserve_type = (e,index) => {   // 选择是否仓储
        chongGouList.value[index].serve_type = e
    }
    const handleChange = (e)=>{
        console.log('选择页码：',e)
        objectData.value.page = e
        handleChongGouList()
    }
    const handlePageSizeChange = (e)=>{
        console.log('选择每页条数：',e)
        objectData.value.page = 1
        objectData.value.pageSize = e
        handleChongGouList()	
    }
    const setSelectedKeys = (ids)=>{
        keys.value = ids
    }
    
    const handleChongGouList = () => {
        predictionManage.getList(objectData.value).then(res => {
            if (res.code == 200) {
                let _data = res.data.items
                _data.map((v, i) => {
                    if (v.load_detail == null) {   // 未生成装卸任务
                        v.load = 3
                    } else if (v.load_detail.detail_load_status == 0) { // 已生成装卸任务
                        v.load = 2
                    } else if (v.load_detail.detail_load_status == 1) { // 已生成装卸任务
                        v.load = 1
                    }
                    v.weight = (v.weight - 0).toFixed(3);
                    v.weight_yu = (v.weight_yu - 0).toFixed(3);
                    v.yb_weight = (v.yb_weight - 0).toFixed(3);
                    v.goods_ids = v.goods_id
                   
                    v.notice_time = tool.dateFormat(
			Math.round(new Date().getTime() / 1000).toString(),
			"yyyy-MM-dd hh:mm:ss"
		),
                    v.transport_type = v.transport_type + ''
                    v.serve_type = v.serve_type + ''
                    v.dept_id = v.dept_id == 0? '' : v.dept_id
                    v.goods_id = v.goods_id == 0? '' : v.goods_id
                    v.contract_id = v.contract_id == 0? '' : v.contract_id
                    if(v.transport_type == 1){
                        v.is_load = true
                    }else{
                        if(v.goods_name.indexOf("石碴") != -1 || v.goods_name.indexOf("碎石") != -1 || v.goods_name.indexOf("重晶石") != -1){
                            v.is_load = true
                        }else{
                            v.is_load = false
                        }
                    }
                    
                });
                console.log('_data:',_data)
                chongGouList.value = _data
                chongGouTotal.value = res.data.pageInfo.total
            }
        })
    }
    const open = (row) => {
        keys.value = []
        handleChongGouList()
        handleDeptList()
        hadnleChangeGoods()
        commonApi.getDict("transport_type").then((res) => {
            yunshuList.value = res.data;
            console.log('yunshuList:',yunshuList.value)
        });
        commonApi.getDict("serve_type").then((res) => {
            fuwuList.value = res.data;
            console.log('fuwuList:',fuwuList.value)
        });
    }
    
    const columns = reactive([
        {
            title: "大票",
            dataIndex: "ec_id",
            align: "center",
            slotName:'ec_id',
            width: 120,
        },
        {
            title: "车号",
            dataIndex: "car_no",
            align: "center",
            formType: "input",
            width: 180,
            slotName:'car_no'
        },
        
        {
            title: "股道",
            dataIndex: "work_line",
            align: "center",
            formType: "input",
            width: 180,
            slotName:'work_line'
        },
        {
            title: "顺位",
            dataIndex: "transport_number",
            align: "center",
            formType: "input",
            width: 180,
            slotName:'transport_number'
        },
        {
            title: "默认装卸",
            dataIndex: "is_load",
            align: "center",
            formType: "switch",
            width: 180,
            slotName:'is_load'
        },
        
        {
            title: "箱号",
            dataIndex: "box",
            formType: "input",
            align: "center",
            width: 160,
            slotName:'box'
        },
        {
            title: "原票号",
            dataIndex: "ticket_number",
            align: "center",
            formType: "input",
            width: 160,
        },
        {
            title: "客户",
            dataIndex: "dept_id",
            align: "center",
            width: 200,
            slotName:'dept_id'
        },
        {
            title: "品名",
            dataIndex: "goods_id",
            align: "center",
            slotName:'goods_id',
            width: 180,
        },
        {
            title: "运输方式",
            dataIndex: "transport_type",
            align: "center",
            slotName:'transport_type',
            width: 120,
        },
        {
            title: "是否仓储",
            dataIndex: "serve_type",
            align: "center",
            slotName:'serve_type',
            width: 120,
        },
        
        
        
        {
            title: "操作",
            dataIndex: "",
            align: "center",
            slotName:'caozuo',
            fixed:'right',
            width: 80,
        },
    ]);



    defineExpose({ open });
</script>
<style>
.input {
	width: 60px;
	padding: 4px 12px;
	background: #fff;
	border: 1px solid rgba(242, 243, 245);
	border-radius: 4px;
	outline: none;
	/*清除input点击之后的黑色边框*/
}

.input:focus {
	background: #fff;
	border: 1px solid #1e80ff;
}

</style>
<script>
export default { name: "prediction:daozhanindex" };
</script>
